# coding=utf-8
"""
Copyright (c) Huawei Technologies Co., Ltd. 2020-2028. All rights reserved.
Description:
FileName：intelligenced.py
Author: h00568282/huangbin
Create Date: 2025/9/9 22:04
Notes:

"""
import json
import logging.config
import os
import socket
import threading

from sys_intd.constant import SOCKET_PATH, LOG_FILE_CONFIG
from sys_intd.executor import CmdExcutor


logging.config.fileConfig(LOG_FILE_CONFIG)
logger = logging.getLogger('sampleLogger')
logging.basicConfig(level=logging.DEBUG)  # 在程序最开头加


class Service:
    def __init__(self, name, command):
        self.name = name
        self.command = command
        self.pid = None
        self.process = None
        self.is_running = False


class ServiceManager:
    def __init__(self):
        self.services: dict[str, Service] = {}
        self.sock = None
        self.cmd_dict = self.init_cmd()

    def init_cmd(self):
        cmd_dict = {
            "search": ['python', 'commands/search.py'],
            "ls": ['python', 'commands/list.py']
        }

        return cmd_dict

    def _ensure_socket_clean(self):
        if os.path.exists(SOCKET_PATH):
            os.unlink(SOCKET_PATH)

    def _handle_client(self, conn, addr):
        try:
            data = conn.recv(4096).decode('utf-8')
            if not data:
                return
            msg = json.loads(data)
            response = CmdExcutor.execute(msg)
            conn.sendall(json.dumps(response).encode('utf-8'))
        except Exception as e:
            conn.sendall(json.dumps({"status": "error", "message": str(e)}).encode('utf-8'))
        finally:
            conn.close()

    def _is_pid_running(self, pid):
        try:
            os.kill(pid, 0)
            return True
        except (ProcessLookupError, OSError):
            return False

    def run(self):
        self._ensure_socket_clean()
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.bind(SOCKET_PATH)
        os.chmod(SOCKET_PATH, 0o666)  # 允许其他用户连接（可根据需求调整权限）
        self.sock.listen(5)
        logger.info(f"🔧 Service Manager is running. Socket: {SOCKET_PATH}")

        try:
            while True:
                conn, addr = self.sock.accept()
                threading.Thread(target=self._handle_client, args=(conn, addr)).start()
        except KeyboardInterrupt:
            logger.error("\n🛑 Shutting down Service Manager...")
        finally:
            if self.sock:
                self.sock.close()
            if os.path.exists(SOCKET_PATH):
                os.unlink(SOCKET_PATH)


def main():
    manager = ServiceManager()
    manager.run()


if __name__ == "__main__":
    main()
